package com.gxuwz.attend.dao.instructor;

import com.gxuwz.attend.entity.Classes;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class ClassesDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Classes> getAllClasses(int size, int offset) {
        String sql = "SELECT * FROM sys_classes LIMIT ? OFFSET ?";
        return jdbcTemplate.query(sql, new Object[]{size, offset}, (rs, rowNum) -> {
            Classes classes = new Classes();
            classes.setClassID(rs.getString("classID"));
            classes.setClassName(rs.getString("className"));
            classes.setDepID(rs.getString("depID"));
            classes.setMajor(rs.getString("major"));
            classes.setGrade(rs.getString("grade"));
            return classes;
        });
    }

    public void addClass(Classes classes) {
        String sql = "INSERT INTO sys_classes(classID, className, depID, major, grade) VALUES(?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, classes.getClassID(), classes.getClassName(), classes.getDepID(), classes.getMajor(), classes.getGrade());
    }

    public void deleteClass(String classID) {
        String sql = "DELETE FROM sys_classes WHERE classID=?";
        int rs = jdbcTemplate.update(sql, classID);
    }

    public void updateClass(Classes classes) {
        String sql = "UPDATE sys_classes SET classID=?, className=?, depID=?, major=?, grade=? WHERE classID=?";
        int rs = jdbcTemplate.update(sql,classes.getClassID(), classes.getClassName(), classes.getDepID(), classes.getMajor(), classes.getGrade(), classes.getId());
    }

    public List<Classes> findClasses(String classID, String className, int size, int offset) {
        // 构建基本的 SQL 查询
        StringBuilder sql = new StringBuilder("SELECT * FROM sys_classes WHERE 1=1");
        List<Object> params = new ArrayList<>();

        // 根据班级ID模糊查询
        if (classID != null && !classID.isEmpty()) {
            sql.append(" AND classID LIKE ?");
            params.add("%" + classID + "%");
        }

        // 根据班级名称模糊查询
        if (className != null && !className.isEmpty()) {
            sql.append(" AND className LIKE ?");
            params.add("%" + className + "%");
        }

        // 添加分页限制
        sql.append(" LIMIT ? OFFSET ?");
        params.add(size);
        params.add(offset);

        // 执行查询并返回结果
        return jdbcTemplate.query(sql.toString(), params.toArray(), (rs, rowNum) -> {
            Classes classes = new Classes();
            classes.setClassID(rs.getString("classID"));
            classes.setClassName(rs.getString("className"));
            classes.setDepID(rs.getString("depID"));
            classes.setMajor(rs.getString("major"));
            classes.setGrade(rs.getString("grade"));
            return classes;
        });
    }
}
